<?php
// +----------------------------------------------------------------------
// | [RhaPHP System] Copyright (c) 2017 http://www.rhaphp.com/
// +----------------------------------------------------------------------
// | [RhaPHP] 并不是自由软件,你可免费使用,未经许可不能去掉RhaPHP相关版权
// +----------------------------------------------------------------------
// | Author: Geeson <qimengkeji@vip.qq.com>
// +----------------------------------------------------------------------


namespace app\mp\controller;



use think\facade\Request;
use think\Validate;
use think\Db;

class   Material extends Base
{


    public function addMaterial($type=1){

        $this->assign('type',$type);
        if (Request::isAjax()) {
            $_data = input();
//            $mp = getMpInfo($this->mid);
//            if ($mp['type'] == 1 || $mp['type'] == 3) {
//                ajaxMsg(0, '此功能认证公众号才能使用');
//            }
            $check_repeat = isset($_data['check_repeat']) ? $_data['check_repeat'] : 0;
            $data['mpid'] = $this->mid;
            if($type == 1){
                $validate = new Validate(
                    [
                        'm_image' => 'require',
                    ],
                    [
                        'm_image.require' => '请上传图片',
                    ]
                );
                $result = $validate->check(input());
                if ($result === false) {
                    ajaxMsg(0, $validate->getError());
                }
                ajaxMsg(1, '上传成功');

//                $F = explode(getHostDomain(), $_data['m_image']);
//                if (isset($F['1'])) {
//                    $filePath = substr($F['1'], 1);
//
//                    if ($result = uploadForeverMedia($filePath, 'image')) {
//
//                        $data['create_time'] = time();
//                        $data['media_id'] = $result['media_id'];
//
//                        $data['url'] = getHostDomain() . url('mp/Show/image','','').'?url='.urlencode($result['url']);
//                        if(!empty($result['url'])){
//                            $model = new \app\common\model\Material();
//                            $model->addMaterialByMp('image', $data);
//                        }
//                        ajaxMsg(1, '上传成功');
//                    }
//                }else{
//                    ajaxMsg(0, '上传失败');
//                }

            }else if($type == 3){
                $validate = new Validate(
                    [
                        'voice_title' => 'require',
                        'm_voice' => 'require',
                    ],
                    [
                        'voice_title.require' => '语音名称不能为空',
                        'm_voice.require' => '请上传语音',
                    ]
                );
                $result = $validate->check(input());
                if ($result === false) {
                    ajaxMsg(0, $validate->getError());
                }

                if($check_repeat == 0){
                    $title = $_data['voice_title'];

                    $rs = $this->checkRepeatMaterial($title,'voice');
                    if($rs['percent'] > 75){
                        ajaxMsg(2, '存在相似音乐【'.$rs['title'].'】，是否继续添加');
                    }
                }

                $data = [
                    'mpid' => $this->mid,
                    'title' => $_data['voice_title'],
                    'url' => $_data['m_voice'],
                    'create_time'=>time()
                ];

                $model = new \app\common\model\Material();
                if($model->addMaterial('voice', $data)){
                    ajaxMsg(1, '上传成功');
                }else{
                    ajaxMsg(0, '上传失败');
                }



//                $F = explode(getHostDomain(), $_data['m_voice']);
//                if (isset($F['1'])) {
//                    $filePath = substr($F['1'], 1);
//
//                    if ($result = uploadForeverMedia($filePath, 'voice')) {
//                        $data = [
//                            'mpid' => $this->mid,
//                            'title' => $_data['video_title'],
//                            'url' => $_data['m_video'],
//                            'media_id' => $result['media_id'],
//                            'create_time'=>time()
//                        ];
//                        if(!empty($result['media_id'])){
//                            $model = new \app\common\model\Material();
//                            $model->addMaterialByMp('voice', $data);
//                        }
//
//                        ajaxMsg(1, '上传成功');
//                    }
//                }else{
//                    ajaxMsg(0, '上传失败');
//                }
            }else if($type == 4){
                $validate = new Validate(
                    [
                        'video_title' => 'require',
                        'm_video' => 'require',
                    ],
                    [
                        'video_title.require' => '视频标题不能为空',
                        'm_video.require' => '请上传视频',
                    ]
                );
                $result = $validate->check(input());
                if ($result === false) {
                    ajaxMsg(0, $validate->getError());
                }

                if($check_repeat == 0){
                    $title = $_data['video_title'];

                    $rs = $this->checkRepeatMaterial($title,'video');
                    if($rs['percent'] > 70){
                        ajaxMsg(2, '存在相似视频【'.$rs['title'].'】，是否继续添加');
                    }
                }

                $data = [
                    'mpid' => $this->mid,
                    'title' => $_data['video_title'],
                    'content' => $_data['video_content'],
                    'url' => $_data['m_video'],

                    'create_time'=>time()
                ];


                $model = new \app\common\model\Material();
                if($model->addMaterial('video', $data)){
                    ajaxMsg(1, '上传成功');
                }else{
                    ajaxMsg(0, '上传失败');
                }


//                $F = explode(getHostDomain(), $_data['m_video']);
//                if (isset($F['1'])) {
//                    $filePath = substr($F['1'], 1);
//
//                    if ($result = uploadForeverMedia($filePath, 'video',true, ['title' => $_data['video_title'], 'introduction' => $_data['video_content']])) {
//
//                        $data = [
//                            'mpid' => $this->mid,
//                            'title' => $_data['video_title'],
//                            'content' => $_data['video_content'],
//                            'url' => $_data['m_video'],
//                            'media_id' => $result['media_id'],
//                            'create_time'=>time()
//                        ];
//
//                        if(!empty($result['media_id'])){
//                            $model = new \app\common\model\Material();
//                            $model->addMaterialByMp('video', $data);
//                        }
//                        ajaxMsg(1, '上传成功');
//                    }
//                }else{
//                    ajaxMsg(0, '上传失败');
//                }
            }

        } else {
            return view();
        }
    }
    public function editMaterial($id=''){
        if (empty($id) ) {
            $this->error('没有相应的内容');
        }
        $material = Db::name('material')->where(['id' => $id,'mpid' => $this->mid])->find();
        if (!$material) {
            $this->error('修改内容不存在或者与公众号不匹配');
        }
        $type = $material['type'];
        if (Request::isAjax()) {
            $_data = input();

             if($type == 'voice'){
                $validate = new Validate(
                    [
                        'voice_title' => 'require',
                        'm_voice' => 'require',
                    ],
                    [
                        'voice_title.require' => '语音名称不能为空',
                        'm_voice.require' => '请上传语音',
                    ]
                );
                $result = $validate->check(input());
                if ($result === false) {
                    ajaxMsg(0, $validate->getError());
                }
                if($material['from_type'] == 0){
                    $data = [
                        'title' => $_data['voice_title'],
                        'url' => $_data['m_voice'],
                    ];

                    $model = new \app\common\model\Material();
                    $model->updateMaterial(['id'=>$id], $data);
                    ajaxMsg(1, '修改成功');
                }else{
                    ajaxMsg(0, '微信素材不能修改');
                }


            }else if($type == 'video'){
                $validate = new Validate(
                    [
                        'video_title' => 'require',
                        'm_video' => 'require',
                    ],
                    [
                        'video_title.require' => '视频标题不能为空',
                        'm_video.require' => '请上传视频',
                    ]
                );
                $result = $validate->check(input());
                if ($result === false) {
                    ajaxMsg(0, $validate->getError());
                }
                 if($material['from_type'] == 0){
                     $data = [
                         'title' => $_data['video_title'],
                         'content' => $_data['video_content'],
                         'url' => $_data['m_video'],
                         'update_time'=>time()
                     ];

                     $model = new \app\common\model\Material();
                     $model->updateMaterial(['id'=>$id], $data);
                     ajaxMsg(1, '修改成功');
                 }else{
                     ajaxMsg(0, '微信素材不能修改');
                 }



            }

        } else {
            $this->assign('material', $material);
            $this->assign('type', $type);
            return view();
        }
    }


    public function addNews()
    {   

        if (Request::isAjax()) {
            $In = Request::post();
            if (empty($In['title'])) {
                ajaxMsg(3, '标题不能为空');
            }
            if (isset($In['content']) && $In['content'] == '`$`') {
                ajaxMsg(3, '请检查必填项');
            }

            $model = new \app\common\model\Material();
            $check_repeat = isset($In['check_repeat']) ? $In['check_repeat'] : 0;

            switch ($In['type']) {
                case 1:
                    if(!$model->addMaterial('text', ['content'=>$In['title'],'mpid' => $this->mid])){
                        ajaxMsg(0, '操作失败了');
                    }
                    break;
                case 2:
                    $array = explode('`|`', $In['content']);

                    if($check_repeat == 0){
                        $title = $array[0];
                        $summary = $array[4];
                        $rs = $this->checkRepeatNews($title,'title');
                        if($rs['percent'] > 70){
                            ajaxMsg(2, '存在相似文章【'.$rs['title'].'】，是否继续添加');
                        }else{
                            $rs = $this->checkRepeatNews($summary,'summary');
                            if($rs['percent'] > 75) {
                                ajaxMsg(2, '存在相似摘要【' . $rs['digest'] . '】，标题【'.$rs['title'].'】，是否继续添加');
                            }
                        }

                    }

                    $news_data['title'] = $array[0];
                    $news_data['author'] = $array[1];
                    $news_data['thumb_url'] = $array[2];
                    $news_data['show_cover_pic'] = $array[3];
                    $news_data['digest'] = $array[4];
                    $news_data['content'] = $array[5];
                    $news_data['content_source_url'] = $array[6];

                    $data = [
                        'mpid' => $this->mid,
                        'title'=> $news_data['title'],
                        'url'=>$news_data['thumb_url'],
                        'description'=>$news_data['digest'],
                        'create_time'=>time(),
                        'type'=>'news'
                    ];

                    $news_id = $model->addMaterial('news', $data);
                    if($news_id){
                        $news_data['news_id'] = $news_id;
                        $news_data['create_time'] = $data['create_time'];
                        $news_data['mpid'] = $this->mid;
                        Db::name('material_news')->insert($news_data);
                    }

                    break;
                case 3:
                    $list = explode('`$`', $In['content']);
                    $news_lists = [];

                    $all_content = [];
                    foreach ($list as $k => $v) {
                        $array = explode('`|`', $v);
                        $news_lists['title'] = $array[0];
                        $news_lists['author'] = $array[1];
                        $news_lists['thumb_url'] = $array[2];
                        $news_lists['show_cover_pic'] = $array[3];
                        $news_lists['digest'] = $array[4];
                        $news_lists['content'] = $array[5];
                        $news_lists['content_source_url'] = $array[6];
                        $all_content[] = $news_lists;
                        if($check_repeat == 0){
                            $title = $array[0];
                            $summary = $array[4];
                            $rs = $this->checkRepeatNews($title,'title');
                            if($rs['percent'] > 70){
                                ajaxMsg(2, '存在相似文章【'.$rs['title'].'】，是否继续添加');
                            }else{
                                $rs = $this->checkRepeatNews($summary,'summary');
                                if($rs['percent'] > 75) {
                                    ajaxMsg(2, '存在相似摘要【' . $rs['digest'] . '】，标题【'.$rs['title'].'】，是否继续添加');
                                }
                            }
                        }

                    }

                    $data = [
                        'mpid' => $this->mid,
                        'title'=>$all_content[0]['title'],
                        'url'=>$all_content[0]['thumb_url'],
                        'description'=>$all_content[0]['digest'],
                        'create_time'=>time(),
                        'type'=>'news'
                    ];

                    $news_id = $model->addMaterial('news', $data);
                    if($news_id){
                        foreach ($all_content as $news_data) {
                            $news_data['news_id'] = $news_id;
                            $news_data['create_time'] = $data['create_time'];
                            $news_data['mpid'] = $this->mid;
                            Db::name('material_news')->insert($news_data);
                        }
                    }

                    ajaxMsg(1, '操作成功');

                    break;
                case 4:
                    $array = explode('`|`', $In['content']);
                    if($check_repeat == 0){
                        $title = $array[0];

                        $rs = $this->checkRepeatMaterial($title,'activity');
                        if($rs['percent'] > 75){
                            ajaxMsg(2, '存在相似活动【'.$rs['title'].'】，是否继续添加');
                        }
                    }

                    $data = [
                        'mpid' => $this->mid,
                        'title' => $array[0],
                        'url'=>$array[1],
                        'description'=>$array[2],
                        'link'=>$array[3],
                        'create_time'=>time(),
                        'type'=>'activity',
                    ];


                    if (!$model->addMaterial('activity', $data)) {

                        ajaxMsg(0, '操作失败了');
                    }
                    break;
            }
            ajaxMsg(1, '操作成功');
        } else {
            $data = input();
            $type = isset($data['type']) ? $data['type'] : 0;
            $this->assign('type', $type);
            $this->assign('uploadImg', getHostDomain() . \url('mp/uploadMediaNewsImage'));
            return view('addnews');
        }
    }
    public function addNews1()
    {
        if (Request::isAjax()) {
            $In = Request::post();
            if (empty($In['title'])) {
                ajaxMsg(3, '标题不能为空');
            }
            if (isset($In['content']) && $In['content'] == '`$`') {
                ajaxMsg(3, '请检查必填项');
            }

            $model = new \app\common\model\Material();
            $custom_message_summary = Db::name('global_config')->where(['code' => 'add_message_summary','admin_id'=>$this->admin_id])->value('value');
            $custom_message_content = Db::name('global_config')->where(['code' => 'add_message_content','admin_id'=>$this->admin_id])->value('value');
            switch ($In['type']) {
                case 2:
                    $array = explode('`|`', $In['content']);
                    $news_lists['title'] = $array[0];
                    $news_lists['author'] = $array[1];
                    $news_lists['cover'] = $array[2];
                    $news_lists['show_cover_pic'] = $array[3];
                    $news_lists['digest'] = $array[4];
                    $news_lists['content'] = $array[5];
                    $news_lists['content_source_url'] = $array[6];
                    $F = explode(getHostDomain(), $news_lists['cover']);

                    if (isset($F['1'])) {
                        $filePath = substr($F['1'], 1);
                        $result = uploadForeverMedia($filePath, 'image');
                    }else{
                        ajaxMsg('0', '图片不存在');
                    }

                    $article_list[0]['thumb_media_id'] = $result['media_id'];
                    $article_list[0]['author'] = $news_lists['author'];
                    $article_list[0]['title'] = $news_lists['title'];
                    $article_list[0]['content_source_url'] = $news_lists['content_source_url'];
                    $article_list[0]['content'] = $news_lists['content'].$custom_message_content;
                    $article_list[0]['digest'] = $news_lists['digest'].$custom_message_summary;
                    $article_list[0]['show_cover_pic'] = $news_lists['show_cover_pic'];

                    $news_data = $article_list[0];
                    $news_data['thumb_url'] = $result['url'];

                    $wxObj = getWechatActiveObj($this->mid);

                    if ($result = $wxObj->uploadForeverArticles(array('articles'=>$article_list))) {

                        $data = [
                            'mpid' => $this->mid,
                            'media_id' => $result['media_id'],
                            'create_time'=>time(),
                            'type'=>'news'
                        ];

                        $news_id = $model->addMaterialByMp('news', $data);
                        if($news_id){
                            $news_data['news_id'] = $news_id;
                            $news_data['create_time'] = $data['create_time'];
                            $news_data['mpid'] = $this->mid;
                            Db::name('material_news')->insert($news_data);
                        }



                    } else {
                        if (isset($wxObj->errCode) && !empty($wxObj->errCode)) {
                            ajaxMsg(0, '上传失败：错误码：' . $wxObj->errCode . ' 错误内容为：' . $wxObj->errMsg);
                        } else {
                            ajaxMsg('0', '未知错误');
                        }
                    }

                    break;
                case 3:
                    $list = explode('`$`', $In['content']);
                    $news_lists = [];
                    $article_list = array();
                    $all_content = [];
                    foreach ($list as $k => $v) {
                        $array = explode('`|`', $v);
                        $news_lists['title'] = $array[0];
                        $news_lists['author'] = $array[1];
                        $news_lists['cover'] = $array[2];
                        $news_lists['show_cover_pic'] = $array[3];
                        $news_lists['digest'] = $array[4];
                        $news_lists['content'] = $array[5];
                        $news_lists['content_source_url'] = $array[6];
                        $F = explode(getHostDomain(), $news_lists['cover']);
                        if (isset($F['1'])) {
                            $filePath = substr($F['1'], 1);

                            $result = uploadForeverMedia($filePath, 'image');

                        }else{
                            ajaxMsg('0', '图片不存在');
                        }

                        $article_list[$k]['thumb_media_id'] = $result['media_id'];
                        $article_list[$k]['author'] = $news_lists['author'];
                        $article_list[$k]['title'] = $news_lists['title'];
                        $article_list[$k]['content_source_url'] = $news_lists['content_source_url'];
                        $article_list[$k]['content'] = $news_lists['content'].$custom_message_content;
                        $article_list[$k]['digest'] = $news_lists['digest'].$custom_message_summary;
                        $article_list[$k]['show_cover_pic'] = $news_lists['show_cover_pic'];
                        $news_item = $article_list[$k];
                        $news_item['thumb_url'] = $result['url'];
                        $all_content[] = $news_item;
                    }

                    $wxObj = getWechatActiveObj($this->mid);
                    if ($result = $wxObj->uploadForeverArticles(array('articles'=>$article_list))) {
                        $data = [
                            'mpid' => $this->mid,
                            'media_id' => $result['media_id'],
                            'create_time'=>time(),
                            'type'=>'news'
                        ];

                        $news_id = $model->addMaterialByMp('news', $data);
                        if($news_id){
                            foreach ($all_content as $news_data) {
                                $news_data['news_id'] = $news_id;
                                $news_data['create_time'] = $data['create_time'];
                                $news_data['mpid'] = $this->mid;
                                Db::name('material_news')->insert($news_data);
                            }
                        }

                        ajaxMsg(1, '操作成功');
                    } else {
                        if (isset($wxObj->errCode) && !empty($wxObj->errCode)) {
                            ajaxMsg(0, '上传失败：错误码：' . $wxObj->errCode . ' 错误内容为：' . $wxObj->errMsg);
                        } else {
                            ajaxMsg('0', '未知错误');
                        }
                    }
                    break;
                case 4:
                    $array = explode('`|`', $In['content']);
                    $data = [
                        'mpid' => $this->mid,
                        'title' => $array[0],
                        'url'=>$array[1],
                        'description'=>$array[2],
                        'link'=>$array[3],
                        'create_time'=>time(),
                        'type'=>'activity'
                    ];

                    if (!$model->addMaterialByMp('activity', $data)) {

                        ajaxMsg(0, '操作失败了');
                    }
                    break;
            }
            ajaxMsg(1, '操作成功');
        } else {
            $data = input();
            $type = isset($data['type']) ? $data['type'] : 0;
            $this->assign('type', $type);
            $this->assign('uploadImg', getHostDomain() . \url('mp/uploadMediaNewsImage'));
            return view('addnews');
        }
    }


    public function editNews($news_id = '')
    {
        
        if (empty($news_id) ) {
            $this->error('没有相应的内容');
        }
        $material = Db::name('material')->where(['id' => $news_id,'mpid' => $this->mid])->find();
        if (!$material) {
            $this->error('修改内容不存在或者与公众号不匹配');
        }

        if (Request::isAjax()) {
            $In = Request::post();
            if (empty($In['title'])) {
                ajaxMsg(3, '标题不能为空');
            }
            if (isset($In['content']) && $In['content'] == '`$`') {
                ajaxMsg(3, '请检查必填项');
            }
            $model = new \app\common\model\Material();

            $check_repeat = isset($In['check_repeat']) ? $In['check_repeat'] : 0;
            switch ($In['type']) {
                case 1:
                    $model->updateMaterial(['id'=>$news_id], ['content'=>$In['title']]);
                    break;
                case 2:
                    $array = explode('`|`', $In['content']);
                    $news_lists['title'] = $array[0];
                    $news_lists['author'] = $array[1];
                    $news_lists['thumb_url'] = $array[2];
                    $news_lists['show_cover_pic'] = $array[3];
                    $news_lists['digest'] = $array[4];
                    $news_lists['content'] = $array[5];
                    $news_lists['content_source_url'] = $array[6];
                    if($check_repeat == 0){
                        $title = $array[0];
                        $summary = $array[4];
                        $rs = $this->checkRepeatNews($title,'title',$news_id);
                        if($rs['percent'] > 70){
                            ajaxMsg(2, '存在相似文章【'.$rs['title'].'】，是否继续添加');
                        }else{
                            $rs = $this->checkRepeatNews($summary,'summary',$news_id);
                            if($rs['percent'] > 75) {
                                ajaxMsg(2, '存在相似摘要【' . $rs['digest'] . '】，标题【'.$rs['title'].'】，是否继续编辑');
                            }
                        }

                    }
                    if($material['from_type'] == 0){
                        $news_data = $news_lists;
                    }else{
                        $F = explode(getHostDomain(), $news_lists['thumb_url']);
                        if (isset($F['1'])) {
                            $filePath = substr($F['1'], 1);
                            $result = uploadForeverMedia($filePath, 'image');
                        }else{
                            ajaxMsg('0', '图片不存在');
                        }
                        $article_list[0]['thumb_media_id'] = $result['media_id'];
                        $article_list[0]['author'] = $news_lists['author'];
                        $article_list[0]['title'] = $news_lists['title'];
                        $article_list[0]['content_source_url'] = $news_lists['content_source_url'];
                        $article_list[0]['content'] = $news_lists['content'];
                        $article_list[0]['digest'] = $news_lists['digest'];
                        $article_list[0]['show_cover_pic'] = $news_lists['show_cover_pic'];
                        $news_data = $article_list[0];

                        $news_data['thumb_url'] = $result['url'];
                    }



                    if($material['from_type'] == 1){
                        $wxObj = getWechatActiveObj($this->mid);
                        if (!$wxObj->updateForeverArticles($material['media_id'],$article_list[0],0)) {
                            if (isset($wxObj->errCode) && !empty($wxObj->errCode)) {
                                ajaxMsg(0, '上传失败：错误码：' . $wxObj->errCode . ' 错误内容为：' . $wxObj->errMsg);
                            } else {
                                ajaxMsg('0', '未知错误');
                            }

                        }
                    }
                    $data = [
                        'title'=> $news_data['title'],
                        'url'=>$news_data['thumb_url'],
                        'description'=>$news_data['digest'],
                        'update_time'=>time(),

                    ];

                    $model->updateMaterial(['id'=>$news_id], $data);


                    Db::name('material_news')->where('news_id', $news_id)->update($news_data);
                    ajaxMsg(1, '修改成功');


                    break;
                case 3:
                    $list = explode('`$`', $In['content']);
                    $news_lists = [];
                    $article_list = array();
                    $all_content = [];
                    foreach ($list as $k => $v) {
                        $array = explode('`|`', $v);
                        $news_lists['title'] = $array[0];
                        $news_lists['author'] = $array[1];
                        $news_lists['thumb_url'] = $array[2];
                        $news_lists['show_cover_pic'] = $array[3];
                        $news_lists['digest'] = $array[4];
                        $news_lists['content'] = $array[5];
                        $news_lists['content_source_url'] = $array[6];
                        if($check_repeat == 0){
                            $title = $array[0];
                            $summary = $array[4];
                            $rs = $this->checkRepeatNews($title,'title',$news_id);
                            if($rs['percent'] > 70){
                                ajaxMsg(2, '存在相似文章【'.$rs['title'].'】，是否继续添加');
                            }else{
                                $rs = $this->checkRepeatNews($summary,'summary',$news_id);
                                if($rs['percent'] > 75) {
                                    ajaxMsg(2, '存在相似摘要【' . $rs['digest'] . '】，标题【'.$rs['title'].'】，是否继续编辑');
                                }
                            }
                        }
                        if($material['from_type'] == 0){
                            $news_lists['news_id'] = $news_id;
                            $news_lists['mpid'] = $this->mid;
                            $news_lists['create_time'] = time();
                            $all_content[] = $news_lists;
                        }else{
                            $F = explode(getHostDomain(), $news_lists['thumb_url']);
                            if (isset($F['1'])) {
                                $filePath = substr($F['1'], 1);

                                $result = uploadForeverMedia($filePath, 'image');

                            }else{
                                ajaxMsg('0', '图片不存在');
                            }

                            $article_list[$k]['thumb_media_id'] = $result['media_id'];
                            $article_list[$k]['author'] = $news_lists['author'];
                            $article_list[$k]['title'] = $news_lists['title'];
                            $article_list[$k]['content_source_url'] = $news_lists['content_source_url'];
                            $article_list[$k]['content'] = $news_lists['content'].$custom_message_content;
                            $article_list[$k]['digest'] = $news_lists['digest'].$custom_message_summary;
                            $article_list[$k]['show_cover_pic'] = $news_lists['show_cover_pic'];
                            $news_item = $article_list[$k];
                            $news_item['thumb_url'] = $result['url'];
                            $news_item['news_id'] = $news_id;
                            $news_item['mpid'] = $this->mid;
                            $news_item['create_time'] = time();
                            $all_content[] = $news_item;
                        }


                    }
                    if($material['from_type'] == 1){
                        $wxObj = getWechatActiveObj($this->mid);
                        foreach ($article_list as $k=>$article) {

                            if (!$wxObj->updateForeverArticles($material['media_id'],$article,$k)) {
                                if (isset($wxObj->errCode) && !empty($wxObj->errCode)) {
                                    ajaxMsg(0, '上传失败：错误码：' . $wxObj->errCode . ' 错误内容为：' . $wxObj->errMsg);
                                } else {
                                    ajaxMsg('0', '未知错误');
                                }

                            }
                        }
                    }
                    $data = [
                        'title'=> $all_content[0]['title'],
                        'url'=>$all_content[0]['thumb_url'],
                        'description'=>$all_content[0]['digest'],
                        'update_time'=>time(),
                    ];

                    $model->updateMaterial(['id'=>$news_id], $data);

                    Db::name('material_news')->where('news_id', $news_id)->delete();

                    if(Db::name('material_news')->insertAll($all_content)){
                        ajaxMsg(1, '修改成功');
                    }else{
                        ajaxMsg(0, '修改失败');
                    }
                    break;
                case 4:
                    $array = explode('`|`', $In['content']);
                    $data = [
                        'title' => $array[0],
                        'url'=>$array[1],
                        'description'=>$array[2],
                        'link'=>$array[3],
                        'update_time'=>time()
                    ];
                    if($check_repeat == 0){
                        $title = $array[0];

                        $rs = $this->checkRepeatMaterial($title,'activity',$news_id);
                        if($rs['percent'] > 75){
                            ajaxMsg(2, '存在相似活动【'.$rs['title'].'】，是否继续编辑');
                        }
                    }
                    $model->updateMaterial(['id'=>$news_id], $data);


                    break;
            }
            ajaxMsg(1, '操作成功');

        } else {
            $newsInfo = Db::name('material')->where(['mpid' => $this->mid, 'id' => $news_id])->find();

            $news_type = $newsInfo['type'];

            $type = '';
            switch ($news_type) {
                case 'text':
                    $type = 1;

                    $this->assign('content', $newsInfo['content']);
                    break;
                case 'news':
                    $type = 2;
                    $news_list = Db::name('material_news')->where(['news_id' => $news_id])->select();
                    $news_count = count($news_list);
                    if($news_count>1){
                        $type = 3;
                        $this->assign('info', $news_list);
                    }else{
                        $this->assign('info', $news_list[0]);
                    }

                    break;

                case 'activity':
                    $type = 4;

                    $this->assign('info', $newsInfo);
                    break;
            }
            $this->assign('news_id', $news_id);
            $this->assign('from_type', $newsInfo['from_type']);
            $this->assign('back_url', getHostDomain() . url('index',['type'=>$material['type'],'from_type'=>$material['from_type'] ]));
            $this->assign('uploadImg', getHostDomain() . \url('uploadMediaNewsImage'));
            $this->assign('type', $type);
            return view('editnews');
        }
    }

    /**
     * 同步公众号素材
     * @author geeson 314835050@qq.com
     * @param string $type
     * @param int $page
     * @return \think\response\View
     */
    public function sycMaterial($type = 'image', $offset = 0)
    {

        $weObj = getWechatActiveObj();
        $count = $weObj->getForeverCount();
        $data['mpid'] = $this->mid;
        $url = '';
        $text = '';
        switch ($type) {
            case 'image':
                $image_count = $count['image_count'];
                $images = getForeverMaterial('image', $offset, 50);
                $i = 0;
                if (!empty($images['item'])) {
                    foreach ($images['item'] as $key => $val) {
                        $i++;
                        $data['create_time'] = $val['update_time'];
                        $data['media_id'] = $val['media_id'];
                        $data['title'] = $val['name'];
                        $data['url'] = getHostDomain() . url('mp/Show/image','','').'?url='.urlencode($val['url']);
                        if(!empty($val['url'])){
                            $model = new \app\common\model\Material();
                            $model->addMaterialByMp($type, $data);
                        }
                    }
                    $url = getHostDomain() . url('mp/Material/sycMaterial', ['type' => $type, 'offset' => $offset + $i]);
                    $jdtCss ='100%'; //ceil(($offset / ($image_count)) * 100) . '%';
                    $text = '正在同步'.$offset.'张图片';
                } else {
                    $text = '同步完成';
                    $url = '';
                    $jdtCss = '100%';
                }
                break;
            case 'voice':
                $voice_count = $count['voice_count'];
                $voice = getForeverMaterial('voice', $offset, 20);
                $i = 0;
                if (!empty($voice['item'])) {
                    foreach ($voice['item'] as $key => $val) {
                        $i++;
                        $data['create_time'] = $val['update_time'];
                        $data['media_id'] = $val['media_id'];
                        $data['title'] = $val['name'];
                        $model = new \app\common\model\Material();
                        $model->addMaterialByMp($type, $data);
                    }
                    $url = getHostDomain() . url('mp/Material/sycMaterial', ['type' => $type, 'offset' => $offset + $i]);
                    $jdtCss = ceil(($offset / $voice_count) * 100) . '%';
                    $text = $jdtCss;
                } else {
                    $text = '同步完成';
                    $url = '';
                    $jdtCss = '100%';
                }
                break;
            case 'video':
                $video_count = $count['video_count'];
                $video = getForeverMaterial('video', $offset, 20);
                $i = 0;
                if (!empty($video['item'])) {
                    foreach ($video['item'] as $key => $val) {
                        $i++;
                        $data['create_time'] = $val['update_time'];
                        $data['media_id'] = $val['media_id'];
                        $data['title'] = $val['name'];
                        $model = new \app\common\model\Material();
                        $model->addMaterialByMp($type, $data);
                    }
                    $url = getHostDomain() . url('mp/Material/sycMaterial', ['type' => $type, 'offset' => $offset + $i]);
                    $jdtCss = ceil(($offset / $video_count) * 100) . '%';
                    $text = $jdtCss;
                } else {
                    $text = '同步完成';
                    $url = '';
                    $jdtCss = '100%';
                }
                break;
            case 'news':
                $news_count = $count['news_count'];
                $news = getForeverMaterial('news', $offset, 20);

                $i = 0;
                if (!empty($news['item'])) {
                    foreach ($news['item'] as $key => $val) {
                        $i++;
                        $data['create_time'] = $val['update_time'];
                        $data['media_id'] = $val['media_id'];
                        if(is_array($news_list = $val['content']['news_item'])){
                            $data['url'] = isset($news_list[0]['thumb_url']) ? $news_list[0]['thumb_url'] : $news_list[0]['url'];
                            $data['title'] = $news_list[0]['title'];
                            $data['description'] = $news_list[0]['digest'];
                        }
                        $model = new \app\common\model\Material();

                        if($news_id = $model->addMaterialByMp($type, $data)){
                            if(isset($val['content']['news_item']) && is_array($news_list = $val['content']['news_item'])){
                                Db::name('material_news')->where(['mpid' => $this->mid, 'news_id' => $news_id])->delete();
                                    foreach ($news_list as $item) {
                                        $news_data = array(
                                            'news_id'=>$news_id,
                                            'mpid'=>$this->mid,
                                            'content'=>$item['content'],
                                            'thumb_url'=>isset($item['thumb_url']) ? $item['thumb_url'] : $item['url'],
                                            'thumb_media_id'=>$item['thumb_media_id'],
                                            'author'=>$item['author'],
                                            'title'=>$item['title'],
                                            'content_source_url'=>$item['content_source_url'],
                                            'digest'=>$item['digest'],
                                            'show_cover_pic'=>$item['show_cover_pic'],
                                            'create_time'=>$val['update_time'],
                                        );
                                        Db::name('material_news')->insert($news_data);
                                    }
                            }
                        }

                    }

                    $url = getHostDomain() . url('mp/Material/sycMaterial', ['type' => $type, 'offset' => $offset + $i]);
                    $jdtCss = ceil(($offset / $news_count) * 100) . '%';
                    $text = $jdtCss;
                } else {

                    $text = '同步完成';
                    $url = '';
                    $jdtCss = '100%';
                }
                break;
        }

        $this->assign('text', $text);
        $this->assign('jdtCss', $jdtCss);
        $this->assign('url', $url);
        return view('syc');
    }



    /**
     * 普通上传图片
     */
    public function uploadImg()
    {

        $file = \request()->file('image');
        $info = $file->rule('md5')->validate(['ext' => 'jpg,png,gif,jpeg'])->move(ROOT_PATH . DS . 'uploads');

        if ($info) {
            $info->getSaveName();
            header('Content-Type:application/json; charset=utf-8');
            $res = [
                'code' => 0,

                'data' => [
                    'src' => getHostDomain() . '/uploads' . DS . $info->getSaveName()
                ]

            ];
            return json_encode($res);

        } else {
            // 上传失败获取错误信息
            $res = [
                'code' => 1,
                'msg' => $file->getError()
            ];
            return json_encode($res);
        }
    }

    public function uploadFileBYmpVerify()
    {
        $file = \request()->file('file');
        $info = $file->validate(['ext' => 'mp3,wma,wav,amr,rm,rmvb,wmv,avi,mpg,mpeg,mp4,txt,zip,rar'])->move(ROOT_PATH . DS, '');

        if ($info) {
            $info->getSaveName();
            header('Content-Type:application/json; charset=utf-8');
            $res = [
                'code' => 0,
                'data' => [
                    'src' => getHostDomain() . '/uploads' . DS . $info->getSaveName()
                ]
            ];
            return json_encode($res);


        } else {
            // 上传失败获取错误信息
            $res = [
                'code' => 1,
                'msg' => $file->getError()
            ];
            return json_encode($res);
        }

    }

    public function index($type = '', $from_type = '')
    {
        $data = input();
        $where = '';
        $keyword = '';
        if(isset($data)){
            if(isset($data['keyword']) && $data['keyword']){
                $keyword = $data['keyword'];
                $where = "(title LIKE '%{$keyword}%' OR title = '{$keyword}')";
            }

        }
        $this->assign('keyword', $keyword);
        if ($type == '' || $from_type == '') {
            $this->redirect('mp/Material/index', ['type' => 'image', 'from_type' => 0]);
        }
        $model = new \app\common\model\Material();
        $data = $model->getMaterialList($type, $this->mid, $from_type, 20,$where);
        if ($type == 'news') {
            $news = [];
            $news_ids = [];
            foreach ($data as $key => $val) {
                $news[$val['id']]['id'] = $val['id'];
                $news[$val['id']]['create_time'] = date('Y-m-d H:i',strtotime($val['create_time']));
                $news[$val['id']]['news_item'] = [];
                $news_ids[] = $val['id'];
            }
            $news_list = Db::name('material_news')->where(['mpid' => $this->mid])->where('news_id','in', $news_ids)->select();

            foreach ($news_list as $item) {
                if($from_type == 1){
                    $item['thumb_url'] = getHostDomain() . url('mp/Show/image','','').'?url='.urlencode($item['thumb_url']);
                }

                $news[$item['news_id']]['news_item'][] = array(
                    'title'=>$item['title'],
                    'id'=>$item['id'],
                    'content_source_url'=>$item['content_source_url'],
                    'thumb_url'=>$item['thumb_url']
                );
            }
            $this->assign('page', $data->render());
            $this->assign('data', $news);
        } else {
            $this->assign('data', $data);
        }

        $this->assign('type', $type);
        $this->assign('from_type', $from_type);
        return view();
    }

    public function sendRecord()
    {
        $data = Db::name('send_record')->where('mpid',$this->mid)->order('id DESC')->paginate(10);
        $news = [];
        $type_list = array(
            'news'=>'图文',
            'image'=>'图片',
            'text'=>'文本'
        );
        foreach ($data as $key => $val) {
            $val['create_time'] = date('Y-m-d H:i',$val['create_time']);
            $val['type_name'] = isset($type_list[$val['type']]) ? $type_list[$val['type']] : '其他';
            if($val['from_type'] == 1){
                $val['url'] = getHostDomain() . url('mp/Show/image','','').'?url='.urlencode($val['url']);
            }else{
                if($val['type'] == 'image'){
                    $val['url'] = getHostDomain() ."/".$val['url'];
                }
            }
            $news[] = $val;
        }

        $this->assign('page', $data->render());

        $this->assign('data', $news);

        return view('sendrecord');
    }
    public function uploadMedia()
    {
        $file = \request()->file('media');
        $info = $file->rule('md5')->validate(['ext' => 'mp3,wma,wav,amr,rm,rmvb,wmv,avi,mpg,mpeg,mp4'])->move(ROOT_PATH . DS . 'uploads');

        if ($info) {
            $info->getSaveName();
            header('Content-Type:application/json; charset=utf-8');
            $res = [
                'code' => 0,
                'data' => [
                    'src' => getHostDomain() . '/uploads' . DS . $info->getSaveName()
                ]
            ];
            return json_encode($res);

        } else {
            // 上传失败获取错误信息
            $res = [
                'code' => 1,
                'msg' => $file->getError()
            ];
            return json_encode($res);
        }
    }
    public function uploadFile()
    {
        $file = \request()->file('media');
        $info = $file->rule('md5')->validate(['ext' => 'mp3,wma,wav,amr,rm,rmvb,wmv,avi,mpg,mpeg,mp4,txt,zip,rar'])->move(ROOT_PATH . DS . 'uploads');

        if ($info) {
            $info->getSaveName();
            header('Content-Type:application/json; charset=utf-8');
            $res = [
                'code' => 0,
                'data' => [
                    'src' => getHostDomain() . '/uploads' . DS . $info->getSaveName()
                ]
            ];
            return json_encode($res);

        } else {
            // 上传失败获取错误信息
            $res = [
                'code' => 1,
                'msg' => $file->getError()
            ];
            return json_encode($res);
        }
    }

    /**
     * 显示二维码图
     * @param $url
     */
    public function qrcode($url)
    {
        header("Content-type: image/png");
        $url = urldecode($url);
        include_once EXTEND_PATH.'/phpqrcode/phpqrcode.php';
        \Qrcode::png($url, $file = false, $level = 'L', $size = 4);
        exit();

    }

    public function getMeterial($type = '', $from_type = 0)
    {
        $model = new \app\common\model\Material();
        $result = $model->getMaterialList($type, $this->mid, $from_type);
        $this->assign('page', $result->render());

        if($from_type == 0){

            $data = [];
            foreach ($result as $k=>$item) {

                $item['url'] = str_replace('\\','/',$item['url']);
                $data[] = $item;
            }
            $result = $data;
        }

        $this->assign('type', $type);
        $this->assign('from_type', $from_type);
        $this->assign('param', input('param'));
        $this->assign('material', $result);
        return view('getmeterial');
    }

    public function getMeterialByImages($type = '', $from_type = 1)
    {
        $model = new \app\common\model\Material();
        $result = $model->getMaterialList($type, $this->mid, $from_type);
        $this->assign('page', $result->render());
        if(($type == 'image' || $type == '') && $from_type == 0){
            $data = [];
            foreach ($result as $k=>$item) {
                $item['url'] = str_replace('\\','/',$item['url']);
                $data[] = $item;
            }
            $result = $data;
        }
        $this->assign('type', $type);
        $this->assign('from_type', $from_type);
        $this->assign('param', input('param'));
        $this->assign('material', $result);
        return view();
    }

    public function sendMaterial($id = '', $type = '',$from_type=0)
    {
        ini_set('max_execution_time', '0');

        if (!$id || !$type) {
            ajaxMsg(0, '参数不完整');
        }

        $mp = getMpInfo($this->mid);
        if ($mp['type'] == 1 || $mp['type'] == 3) {
            ajaxMsg(0, '此功能认证公众号才能使用');
        }
        $model = new \app\common\model\Material();
        if($type!="news"&& $type!="image" &&$type!="text" ){
            ajaxMsg(0, '此类型素材不能群发');
        }
        if($type == 'image' && $from_type==0){

            $material =  Db::name('picture')->where(['mpid'=>$this->mid,'id'=>$id])
                ->where('type',1)
                ->field('mpid,picture as url')
                ->find();
            $material['type'] = 'image';

        }else{
            $material = $model->where(['id'=>$id,'type'=>$type,'from_type'=>$from_type])->find();

        }

        if(!$material){
            ajaxMsg(0, '素材不存在');
        }
        $wxObj = getWechatActiveObj($this->mid);
        if($type != 'text'){

            $custom_message_summary = Db::name('global_config')->where(['code' => 'add_message_summary', 'admin_id' => $this->admin_id])->value('value');
            $custom_message_content = Db::name('global_config')->where(['code' => 'add_message_content', 'admin_id' => $this->admin_id])->value('value');
            if($from_type == 1 && ($type != 'news' || (!$custom_message_summary && !$custom_message_content))){
                $media_id = $material['media_id'];

            }else {
                if ($type == 'news') {

                    $lists = Db::name('material_news')->where('news_id', $id)->select();
                    if (empty($lists))
                        ajaxMsg('0', '没有内容可上传');

                    $material['description'] .= $custom_message_summary;
                    $material['content'] .= $custom_message_content;
                    foreach ($lists as $key => $val) {
                        $F = explode(getHostDomain(), $val['thumb_url']);
                        if (isset($F['1'])) {
                            $filePath = substr($F['1'], 1);
                            //为了不占用5000张素材空间，这里上传为临时素材，有效果为3天
                            if ($result = uploadMedia($filePath, 'image')) {
                                $lists[$key]['thumb_media_id'] = $result['media_id'];
                                $model->save(['thumb_media_id' => $result['media_id']], ['id' => $val['id']]);
                            }
                        }
                        $array[$key]['thumb_media_id'] = $lists[$key]['thumb_media_id'];
                        $array[$key]['author'] = $val['author'];
                        $array[$key]['title'] = $val['title'];
                        $array[$key]['content_source_url'] = $val['content_source_url'];
                        $array[$key]['content'] = $val['content'] . $custom_message_content;
                        $array[$key]['digest'] = $val['digest'] . $custom_message_summary;
                        $array[$key]['show_cover_pic'] = $val['show_cover_pic'];

                    }
                    $articleList['articles'] = $array;

                    if ($result = $wxObj->uploadArticles($articleList)) {
                        $media_id = $result['media_id'];

                    } else {
                        if (isset($wxObj->errCode) && !empty($wxObj->errCode)) {
                            ajaxMsg(0, '群发失败：错误码：' . $wxObj->errCode . ' 错误内容为：' . $wxObj->errMsg);
                        } else {
                            ajaxMsg('0', '未知错误');
                        }
                    }

                } else {
                    //为了不占用5000张素材空间，这里上传为临时素材，有效果为3天
                    if ($result = uploadMedia($material['url'], 'image')) {
                        $media_id = $result['media_id'];
                    }

                }
            }

            if(!isset($media_id)){
                ajaxMsg(0, '群发失败');
            }
        }


            if ($type == 'news') {
                $data = [
                    'filter' => [
                        'is_to_all' => true
                    ],
                    'msgtype' => 'mpnews',
                    'mpnews' => [
                        'media_id' => $media_id
                    ],
                    'send_ignore_reprint' => 0
                ];
            } else  if ($type == 'image') {
                $data = [
                    'filter' => [
                        'is_to_all' => true,     //是否群发给所有用户.True不用分组id，False需填写分组id

                    ],
                    'image' =>
                        ["media_id" => $media_id]
                    ,
                    'msgtype' => 'image',
                ];
            }else{
                $data = [
                        'filter' => [
                            'is_to_all' => true,
                            'tag_id' => ''
                        ],
                        'text' => [
                            'content' => $material['content'],
                        ],
                        'msgtype' => 'text',

                    ];
            }


            $this->SynFriends();
            $result = $wxObj->sendGroupMassMessage($data);
            if ($result && isset($result['errcode']) && $result['errcode'] == 0) {
                $insert_data = array(
                    'mpid'=>$material['mpid'],
                    'type' => isset($material['type']) ? $material['type'] : '',
                    'title' => isset($material['title']) ? $material['title'] : '',
                    'url' => isset($material['url']) ? $material['url'] : '',
                    'description' => isset($material['description']) ? $material['description'] : '',
                    'content' => isset($material['content']) ? $material['content'] : '',
                    'detail' => isset($material['detail']) ? $material['detail'] : '',
                    'link' => isset($material['link']) ? $material['link'] : '',
                    'media_id' => isset($material['media_id']) ? $material['media_id'] : '',
                    'from_type' => isset($material['from_type']) ? $material['from_type'] : 0,
                    'path'=>isset($material['path']) ? $material['path'] : '',
                    'create_time' => time(),
                );
                Db::name('send_record')->insert($insert_data);
                ajaxMsg(1, '群发成功');
            } else {
                if($wxObj->errCode == 45028){
                    ajaxMsg(0, '群发失败， 错误内容：今日群发次数已用完');
                }else{
                    ajaxMsg(0, '群发失败，错误码：' . $wxObj->errCode . ' 错误内容：' . $wxObj->errMsg);
                }

            }


    }

    public function delMaterial($id = '', $type = '',$from_type=0)
    {
        if (!$id || !$type) {
            ajaxMsg(0, '参数不完整');
        }
        $model = new \app\common\model\Material();
        if($from_type == 1){
            $material = $model->where(['id'=>$id,'type'=>$type,'from_type'=>$from_type])->find();
            if(!$material){
                ajaxMsg('0', '素材不存在');
            }

            $res = $model->delMaterial($material['media_id'], $this->mid);


        }else{
            if($type == 'image'){
                $res = Db::name('picture')->where(['id' => $id, 'mpid' => $this->mid])->delete();
            }else{
                $res = $model->where(['id' => $id, 'type'=>$type,'mpid' => $this->mid])->delete();
            }

        }
        if ($res){
            if($type=='news'){
                Db::name('material_news')->where(['news_id' => $id])->delete();
            }
            ajaxMsg('1', '删除成功');
        }

        else
            ajaxMsg('0', '删除失败');




    }

    public function newsPreview($id = '', $type = '',$from_type=0)
    {
        if (!$id || !$type) {
            ajaxMsg(0, '参数不完整');
        }

        $mp = getMpInfo($this->mid);
        if ($mp['type'] == 1 || $mp['type'] == 3) {
            ajaxMsg(0, '此功能认证公众号才能使用');
        }
        $model = new \app\common\model\Material();
        if($type!="news"&& $type!="image" && $type!="text" ){
            ajaxMsg(0, '此类型素材不能群发');
        }
        if($type == 'image' && $from_type==0){

            $material =  Db::name('picture')->where(['mpid'=>$this->mid,'id'=>$id])
                ->where('type',1)
                ->field('picture as url')
                ->find();


        }else{
            $material = $model->where(['id'=>$id,'type'=>$type,'from_type'=>$from_type])->find();
            $from_type = $material['from_type'];
        }

        if(!$material){
            ajaxMsg(0, '素材不存在');
        }
        $wxObj = getWechatActiveObj($this->mid);
        if($type != 'text'){
            if($from_type == 1){
                $media_id = $material['media_id'];

            }else {
                if ($type == 'news') {
                    $lists = Db::name('material_news')->where('news_id', $id)->select();
                    if (empty($lists))
                        ajaxMsg('0', '没有内容可上传');

                    $custom_message_summary = Db::name('global_config')->where(['code' => 'add_message_summary', 'admin_id' => $this->admin_id])->value('value');
                    $custom_message_content = Db::name('global_config')->where(['code' => 'add_message_content', 'admin_id' => $this->admin_id])->value('value');

                    foreach ($lists as $key => $val) {
                        $F = explode(getHostDomain(), $val['thumb_url']);
                        if (isset($F['1'])) {
                            $filePath = substr($F['1'], 1);
                            //为了不占用5000张素材空间，这里上传为临时素材，有效果为3天
                            if ($result = uploadMedia($filePath, 'image')) {
                                $lists[$key]['thumb_media_id'] = $result['media_id'];
                                $model->save(['thumb_media_id' => $result['media_id']], ['id' => $val['id']]);
                            }
                        }
                        $array[$key]['thumb_media_id'] = $lists[$key]['thumb_media_id'];
                        $array[$key]['author'] = $val['author'];
                        $array[$key]['title'] = $val['title'];
                        $array[$key]['content_source_url'] = $val['content_source_url'];
                        $array[$key]['content'] = $val['content'] . $custom_message_content;
                        $array[$key]['digest'] = $val['digest'] . $custom_message_summary;
                        $array[$key]['show_cover_pic'] = $val['show_cover_pic'];

                    }
                    $articleList['articles'] = $array;

                    if ($result = $wxObj->uploadArticles($articleList)) {
                        $media_id = $result['media_id'];

                    } else {
                        if (isset($wxObj->errCode) && !empty($wxObj->errCode)) {
                            ajaxMsg(0, '预览失败：错误码：' . $wxObj->errCode . ' 错误内容为：' . $wxObj->errMsg);

                        } else {
                            ajaxMsg('0', '未知错误');
                        }
                    }

                } else {
                    //为了不占用5000张素材空间，这里上传为临时素材，有效果为3天
                    if ($result = uploadMedia($material['url'], 'image')) {
                        $media_id = $result['media_id'];
                    }

                }
            }
            if(!isset($media_id)){
                ajaxMsg(0, '群发失败');
            }
        }

        $wxid = Request::post('wxid');
        if ($type == 'news') {

            $data = [
                'towxname' => $wxid,
                'msgtype' => 'mpnews',
                'mpnews' => [
                    'media_id' => $media_id
                ],

            ];
        } else if ($type == 'image') {
            $data = [
                'towxname' => $wxid,
                'msgtype' => 'image',
                'image' =>
                    ["media_id" => $media_id]

            ];

        }else  {

            $data = [
                'towxname' => $wxid,
                'text' => [
                    'content' => $material['content'],
                ],
                'msgtype' => 'text',
            ];
        }

        $wxObj = getWechatActiveObj($this->mid);
        $result = $wxObj->previewMassMessage($data);
        if ($result && isset($result['errcode']) && $result['errcode'] == 0) {
            ajaxMsg(1, '发送成功，请打开发送者微信进行预览');
        } else {
            if($wxObj->errCode == 43004){
                ajaxMsg(0, '预览失败：错误内容为：请先关注此公众号');
            }else{
                ajaxMsg(0, '发送失败，错误码：' . $wxObj->errCode . ' 错误内容：' . $wxObj->errMsg);
            }


        }


    }

    public function SynFriends()
    {

        $wechatObj = getWechatActiveObj($this->mid);
        $table = config('database.prefix') . 'syn_openid';
        $finish = 1;
        $next_openid =  null;
        $friendTotal = 0;
        $page = 0;
        while ($finish == 1) {
            $opneidTotal = Db::name('syn_openid')->where('mpid', '=', $this->mid)->count('distinct(openid)');
            $sql = "DELETE FROM {$table} WHERE openid IN (SELECT * FROM(SELECT openid FROM {$table} WHERE mpid = {$this->mid}  GROUP BY openid HAVING COUNT(openid) > 1) AS b) AND id NOT IN (SELECT * FROM (SELECT MIN(id) FROM {$table} WHERE mpid = {$this->mid}  GROUP BY openid HAVING COUNT(openid) > 1) AS c)";
            Db::execute($sql);
            if ($opneidTotal >= $friendTotal && $friendTotal > 0) {
                $synOpenids = Db::name('syn_openid')->where('mpid', '=', $this->mid)
                    ->distinct(true)
                    ->field('openid')
                    ->limit(100 * $page,100)->select();
                if (!empty($synOpenids)) {
                    $openids['user_list'] = [];
                    foreach ($synOpenids as $key => $val) {
                        $openids['user_list'][$key]['openid'] = $val['openid'];
                    }
                    $friends_array = $wechatObj->getUsersInfo($openids);
                    if (isset($friends_array['user_info_list']) && is_array($friends_array['user_info_list'])) {
                        foreach ($friends_array['user_info_list'] as $value) {
                            $value['mpid'] = $this->mid;
                            $value['tagid_list'] = @json_encode($value['tagid_list'], true);
                            if (Db::name('mp_friends')->where(['mpid' => $this->mid, 'openid' => $value['openid']])->field('id')->find()) {
                                Db::name('mp_friends')->where(['mpid' => $this->mid, 'openid' => $value['openid']])->update($value);
                            } else {
                                Db::name('mp_friends')->insert($value);
                            }
                        }
                    }
                    $page = $page+1;
                } else {
                    $finish = 2;
                    Db::name('syn_openid')->where('mpid', '=', $this->mid)->delete();
                }

            } else {
                $friendList = $wechatObj->getUserList($next_openid);
                $friendTotal = $friendList['total'];
                if (!empty($friendList) && $friendList['count'] > 0) {
                    $openids = array_chunk($friendList['data']['openid'], 5000);
                    foreach ($openids as $key => $val) {
                        foreach ($val as $key1 => $opneid) {
                            $openid_list[$key][$key1] = [
                                'openid' => $opneid,
                                'mpid' => $this->mid
                            ];
                        }
                        Db::name('syn_openid')->insertAll($openid_list[$key]);
                    }
                    $next_openid = $friendList['next_openid'];

                } else {
                    if ($wechatObj->errCode != '40001' && $wechatObj->errCode != '' && $wechatObj->errMsg != '') {
                        if ($msg = wxApiResultErrorCode($wechatObj->errCode)) {
                            return $msg;
                        } else {
                            return 'errCode:' . $wechatObj->errCode . 'errMsg:' . $wechatObj->errMsg;
                        }
                    }
                    $finish = 2;
                }
            }
        }
        return 1;




    }
    public function uploadMediaNews($id = '', $type = '')
    {
        if (!$id || !$type) {
            ajaxMsg(0, '参数不完整');
        }

        $mp = getMpInfo($this->mid);
        if ($mp['type'] == 1 || $mp['type'] == 3) {
            ajaxMsg(0, '此功能认证公众号才能使用');
        }
        $model = new \app\common\model\Material();


        if($type == 'image' ){

            $material =  Db::name('picture')->where(['mpid'=>$this->mid,'id'=>$id])
                ->where('type',1)
                ->field('picture as url')
                ->find();
            if ($result = uploadForeverMedia($material['url'], 'image')) {

                $data['create_time'] = time();
                $data['media_id'] = $result['media_id'];

                $data['url'] = getHostDomain() . url('mp/Show/image','','').'?url='.urlencode($result['url']);
                if(!empty($result['url'])){

                    $model->addMaterialByMp('image', $data);
                }
                ajaxMsg(1, '上传成功');
            }else{
                ajaxMsg(1, '上传失败');
            }

        }else if($type == 'voice'){
            $material = $model->where(['id'=>$id,'type'=>$type])->find();
            $F = explode(getHostDomain(), $material['url']);
            if (isset($F['1'])) {
                $filePath = substr($F['1'], 1);

                if ($result = uploadForeverMedia($filePath, 'voice')) {
                    $data = [
                        'mpid' => $this->mid,
                        'title' => $material['title'],
                        'url' => $material['url'],
                        'media_id' => $result['media_id'],
                        'create_time'=>time()
                    ];
                    if(!empty($result['media_id'])){
                        $model->addMaterialByMp('voice', $data);
                    }

                    ajaxMsg(1, '上传成功');
                }
            }else{
                ajaxMsg(0, '上传失败');
            }

        }
        else if($type == 'video'){
            $material = $model->where(['id'=>$id,'type'=>$type])->find();
            $F = explode(getHostDomain(), $material['url']);
                if (isset($F['1'])) {
                    $filePath = substr($F['1'], 1);

                    if ($result = uploadForeverMedia($filePath, 'video',true, ['title' => $material['title'], 'introduction' => $material['content']])) {

                        $data = [
                            'mpid' => $this->mid,
                            'title' => $material['title'],
                            'content' => $material['content'],
                            'url' => $material['url'],
                            'media_id' => $result['media_id'],
                            'create_time'=>time()
                        ];

                        if(!empty($result['media_id'])){
                            $model->addMaterialByMp('video', $data);
                        }
                        ajaxMsg(1, '上传成功');
                    }
                }else{
                    ajaxMsg(0, '上传失败');
                }

        }else if($type == 'news'){
            $lists = Db::name('material_news')->where('news_id', $id)->select();
            if (empty($lists))
                ajaxMsg('0', '没有内容可上传');

            $custom_message_summary = Db::name('global_config')->where(['code' => 'add_message_summary', 'admin_id' => $this->admin_id])->value('value');
            $custom_message_content = Db::name('global_config')->where(['code' => 'add_message_content', 'admin_id' => $this->admin_id])->value('value');

            foreach ($lists as $key => $val) {
                $F = explode(getHostDomain(), $val['thumb_url']);
                if (isset($F['1'])) {
                    $filePath = substr($F['1'], 1);

                    if ($result = uploadForeverMedia($filePath, 'image')) {
                        $lists[$key]['thumb_media_id'] = $result['media_id'];
                        $lists[$key]['thumb_url'] = $result['url'];
                        $model->save(['thumb_media_id' => $result['media_id']], ['id' => $val['id']]);
                    }
                }
                $array[$key]['thumb_media_id'] = $lists[$key]['thumb_media_id'];
                $array[$key]['author'] = $val['author'];
                $array[$key]['title'] = $val['title'];
                $array[$key]['content_source_url'] = $val['content_source_url'];
                $array[$key]['content'] = $val['content'] . $custom_message_content;
                $array[$key]['digest'] = $val['digest'] . $custom_message_summary;
                $array[$key]['show_cover_pic'] = $val['show_cover_pic'];
                $news_item = $array[$key];
                $news_item['thumb_url'] = $lists[$key]['thumb_url'];
                $all_content[] =  $news_item;
            }
            $articleList['articles'] = $array;
            $wxObj = getWechatActiveObj($this->mid);

            if ($result = $wxObj->uploadForeverArticles($articleList)) {

                $data = [
                    'mpid' => $this->mid,
                    'media_id' => $result['media_id'],
                    'url'=>$all_content[0]['thumb_url'],
                    'title'=>$all_content[0]['title'],
                    'description'=>$all_content[0]['digest'],
                    'create_time'=>time(),
                    'type'=>'news'
                ];

                $news_id = $model->addMaterialByMp('news', $data);
                if($news_id){
                    foreach ($all_content as $news_data) {
                        $news_data['news_id'] = $news_id;
                        $news_data['create_time'] = $data['create_time'];
                        $news_data['mpid'] = $this->mid;
                        Db::name('material_news')->insert($news_data);
                    }
                }

                ajaxMsg(1, '上传成功');
            } else {
                if (isset($wxObj->errCode) && !empty($wxObj->errCode)) {
                    ajaxMsg(0, '上传失败：错误码：' . $wxObj->errCode . ' 错误内容为：' . $wxObj->errMsg);
                } else {
                    ajaxMsg('0', '未知错误');
                }
            }

        }


    }

    function deleteRecord($id=''){
        Db::name('send_record')->where(['id' => $id])->delete();
    }

    function combineNews(){
        $news_ids = Request::post('ids');
        $ids = explode(',',$news_ids);


        if(is_array($ids)){
            $model = new \app\common\model\Material();
            $lists = [];
            foreach ($ids as $id) {
                $lists[] = Db::name('material_news')->where('id',$id)->find();
            }
            if(!$lists){
                ajaxMsg('0', '素材不存在');
            }

            $data = [
                'mpid' => $this->mid,
                'title'=>$lists[0]['title'],
                'url'=>$lists[0]['thumb_url'],
                'description'=>$lists[0]['digest'],
                'create_time'=>time(),
                'type'=>'news'
            ];

            $news_id = $model->addMaterial('news', $data);
            if($news_id){
                foreach ($lists as $news_data) {
                    unset($news_data['id']);
                    $news_data['news_id'] = $news_id;
                    $news_data['create_time'] = $data['create_time'];
                    $news_data['mpid'] = $this->mid;

                    Db::name('material_news')->insert($news_data);
                }
                ajaxMsg('1', '合并成功，请在本地素材里查看');
            }else{
                ajaxMsg('0', '合并失败');
            }


        }else{
            ajaxMsg('0', '合并失败');
        }

    }


    function str_split_unicode($str, $l = 0,$length=10) {

        if ($l > 0) {

            $ret = array();
            $len = mb_strlen($str, "UTF-8");
            if($len < $length){
                $length = $len;
            }
            for ($i = 0; $i < $length; $i += ($l+1)) {
                $ret[] = mb_substr($str, $i, $l, "UTF-8");
            }
            return $ret;
        }
        return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
    }
    function checkRepeatNews($text,$type,$news_id=0){
        if($type == 'title'){
            $where = '0';
            if(strlen($text) > 5){
                $words = $this->str_split_unicode($text,3,15);
                foreach ($words as $item) {
                    if(strlen($item)>1){
                        $where .= " OR title like '%{$item}%'";
                    }

                }
            }
            if(strlen($text) > 3){
                $words = $this->str_split_unicode($text,2);
                foreach ($words as $item) {
                    if(strlen($item)>1){
                        $where .= " OR title like '%{$item}%'";
                    }

                }
            }else{
                $where = " title = '{$text}'";
            }

            $news_list = Db::name('material_news')->where('news_id',"<>",$news_id)->where(['mpid'=>$this->mid])->where($where)->limit(20)->field('title')->select();

            $similar_news = '';
            $percent = 0;
            foreach ($news_list as $item) {
                similar_text($text,$item['title'],$now_percent);
                if($now_percent > $percent){
                    $percent = $now_percent;
                    $similar_news = $item['title'];
                }
            }
            return array(
                'percent'=>$percent,
                'title'=>$similar_news
            );


        }else if($type == 'summary'){
            $where = '0';
            if(strlen($text) > 5){
                $words = $this->str_split_unicode($text,3,15);
                foreach ($words as $item) {
                    if(strlen($item)>1){
                        $where .= " OR digest like '%{$item}%'";
                    }

                }
            }
            if(strlen($text) > 3){
                $words = $this->str_split_unicode($text,2);
                foreach ($words as $item) {
                    if(strlen($item)>1){
                        $where .= " OR digest like '%{$item}%'";
                    }

                }
            }else{
                $where = " digest = '{$text}'";
            }

            $news_list = Db::name('material_news')->where('news_id',"<>",$news_id)->where(['mpid'=>$this->mid])->where($where)->limit(10)->field('title,digest')->select();

            $similar_news = '';
            $percent = 0;
            $digest = '';
            foreach ($news_list as $item) {
                similar_text($text,$item['digest'],$now_percent);
                if($now_percent > $percent){
                    $percent = $now_percent;
                    $similar_news = $item['title'];
                    $digest = $item['digest'];
                }
            }
            return array(
                'percent'=>$percent,
                'title'=>$similar_news,
                'digest'=>$digest,

            );

        }
    }
    function checkRepeatMaterial($text,$type,$id=0){

            $where = '0';
            if(strlen($text) > 5){
                $words = $this->str_split_unicode($text,3,15);
                foreach ($words as $item) {
                    if(strlen($item)>1){
                        $where .= " OR title like '%{$item}%'";
                    }

                }
            }
            if(strlen($text) > 3){
                $words = $this->str_split_unicode($text,2);
                foreach ($words as $item) {
                    if(strlen($item)>1){
                        $where .= " OR title like '%{$item}%'";
                    }

                }
            }else{
                $where = " title = '{$text}'";
            }

            $news_list = Db::name('material')->where('id','<>',$id)->where(['mpid'=>$this->mid,'type'=>$type])->where($where)->limit(20)->field('title')->select();

            $similar_news = '';
            $percent = 0;
            foreach ($news_list as $item) {
                similar_text($text,$item['title'],$now_percent);
                if($now_percent > $percent){
                    $percent = $now_percent;
                    $similar_news = $item['title'];
                }
            }
            return array(
                'percent'=>$percent,
                'title'=>$similar_news
            );


    }

}